﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using System.Text;
using System.Windows.Forms;
using UCL;
using UCL.Data;

namespace DBKit5
{
    /// <summary>
    /// 2013-6-7 by sutroon
    /// </summary>
    class AppDataHelper : SQLiteHelper
    {
        public static bool APP_DEBUG { get; set; }
        public AppDataHelper()
            : base("Data Source=DBKitDB.db;Pooling=true;FailIfMissing=false")
        {
            base.ExecuteNonQuery("create table if not exists tgeneralcatalog (ID INTEGER PRIMARY KEY, Name text, ParentID int not null default 0, Content text, ExTags text, Ordinal smallint not null default 999, SiteTag text)");
            base.ExecuteNonQuery("create table if not exists tconnections (ID INTEGER PRIMARY KEY, GroupID int not null default 0, Name text, HostName text, Port int, LoginID text, Password text, Database text, ProductName text, Ordinal smallint not null default 999, IsDefault bit, ExTags text, CreatedTime DateTime not null default CURRENT_TIMESTAMP)");
        }

        /// <summary>
        /// 获取指定数据库类型的数据库助手类 2013-6-8 by sutroon
        /// </summary>
        /// <param name="dbType"></param>
        /// <param name="hostname"></param>
        /// <param name="loginid"></param>
        /// <param name="password"></param>
        /// <param name="database"></param>
        /// <returns></returns>
        public IDatabaseHelper GetDatabaseHelper(string dbType, string hostname = "", string loginid = "", string password = "", string database = "")
        {
            IDatabaseHelper idh;
            switch (dbType)
            {
                case "SQLServer":
                    idh = new SQLServerHelper("");
                    break;
                case "MySQL":
                    idh = new MySQLHelper("");
                    break;
                case "SQLite":
                    idh = new SQLiteHelper("");
                    break;
                default:
                    return null;
            }
            if (hostname.Length > 0) idh.ConnectionString = idh.GetConnectionString(hostname, loginid, password, database);
            return idh;
        }

        /// <summary>
        /// 测试连接是否正常
        /// <para>2013-8-2 by sutroon</para>
        /// </summary>
        /// <param name="dbType"></param>
        /// <param name="hostName"></param>
        /// <param name="port"></param>
        /// <returns></returns>
        internal bool TestConnection(string dbType, string hostName, int port = 0)
        {
            switch (dbType)
            {
                case "SQLServer":
                case "MySQL":
                    if (!IPHelper.TestConnection(hostName.ToString(), port))
                    {
                        MessageBox.Show(string.Format("[{0}] 连接失败", hostName));
                        return false;
                    }
                    return true;
                case "SQLite":
                    if (!System.IO.File.Exists(hostName))
                    {
                        MessageBox.Show(string.Format("[{0}] 连接失败", hostName));
                        return false;
                    }
                    return true;
            }
            return false;
        }

        /// <summary>
        /// 获取分类属性字符串
        /// </summary>
        /// <param name="exTags"></param>
        /// <param name="parentID"></param>
        /// <returns></returns>
        /// <remarks>1.0.0 2013-10-17 sutroon</remarks>
        internal string GetCatalogTreeText(string exTags, int parentID = 0)
        {
            return base.ExecuteTreeXml("select ID, Name from tgeneralcatalog where ParentID={0} and ExTags='" + exTags + "'", parentID.ToString());
        }

        /// <summary>
        /// 获取连接组的字符串
        /// </summary>
        /// <param name="exTags"></param>
        /// <param name="parentId"></param>
        /// <returns></returns>
        /// <remarks>2014-3-19 by sutroon</remarks>
        public string GetConnectionGroupTreeXml(string exTags, string parentId = "0")
        {
            return base.ExecuteTreeXml(string.Format("select ID, Name from tGeneralCatalog where ParentID='{{0}}' and ExTags='{0}'", exTags), parentId, "Select ID, Name from tConnections where GroupID='{0}'");
        }

        /// <summary>
        /// 分发脚本到指定数据库
        /// </summary>
        /// <param name="ids"></param>
        /// <param name="sql"></param>
        /// <returns></returns>
        /// <remarks>2014-3-19 by sutroon</remarks>
        public string RunDistributeScript(IList<string> ids,string sql)
        {
            IDatabaseHelper idh;
            List<string> msg = new List<string>();
            DataTable dt = base.SelectDataTable("tConnections", string.Format("ID in ({0})", ids.ToString(",", "'{0}'")), "*");
            foreach (DataRow row in dt.Rows)
            {
                idh = this.GetDatabaseHelper(row["ProductName"].ToString(), row["HostName"].ToString(), row["LoginID"].ToString(), row["Password"].ToString(), row["Database"].ToString());
                try
                {
                    idh.ExecuteNonQuery(sql);
                }
                catch (Exception ex)
                {
                    msg.Add(ex.Message);
                }
            }
            return msg.Count > 0 ? msg.ToString(Environment.NewLine) : "SUCCESS";
        }


        // 获取关于我们的的简介
        public static string GetAboutText()
        {
            StringBuilder sbAbout = new StringBuilder();
            sbAbout.AppendLine("DBKit-数据库工具箱 (DBKit5 2014.1.21)");
            sbAbout.AppendLine("本程序支持多重数据库,支持很多日常数据库维护的快捷操作，是您项目开发的好帮手~");
            sbAbout.AppendLine("本程序版权归天澜(14507247@qq.com | SoChishun.Com)");
            sbAbout.AppendLine("如果您有什么建议或者发现BUG，请致信14507247@qq.com，万分感谢~");
            return sbAbout.ToString();
        }
    }
}
